package com.libertyville.application.orgmng;

import com.libertyville.domain.orgmng.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrgService {
    private OrgBuilderFactory orgBuilderFactory;
    private OrgRepository orgRepository;
    private OrgHandler orgHandler;

    @Autowired
    public OrgService(OrgBuilderFactory orgBuilderFactory, OrgRepository orgRepository, OrgHandler orgHandler) {
        this.orgBuilderFactory = orgBuilderFactory;
        this.orgRepository = orgRepository;
        this.orgHandler = orgHandler;
    }

    @Transactional
    public OrgResponse addOrg(CreateOrgRequest request, String createdBy) {
        OrgBuilder orgBuilder = orgBuilderFactory.create();
        Org org = orgBuilder.tenantId(request.getTenantId())
                .superiorId(request.getSuperiorId())
                .leaderId(request.getLeaderId())
                .name(request.getName())
                .orgTypeCode(request.getOrgTypeCode())
                .createdBy(createdBy)
                .buildOrg();
        Org saved = orgRepository.saveOrg(org);
        return buildOrgResponse(saved);
    }

    private OrgResponse buildOrgResponse(Org saved) {
        OrgResponse orgResponse = new OrgResponse();
        orgResponse.setId(saved.getOrgId());
        orgResponse.setTenantId(saved.getTenantId());
        orgResponse.setSuperiorId(saved.getSuperiorId());
        orgResponse.setLeaderId(saved.getLeaderId());
        orgResponse.setName(saved.getName());
        orgResponse.setOrgTypeCode(saved.getOrgTypeCode());
        orgResponse.setStatusCode(saved.getOrgStatus().getCode());
        orgResponse.setCreatedAt(saved.getCreatedAt());
        orgResponse.setCreatedBy(saved.getCreatedBy());
        orgResponse.setLastUpdatedAt(saved.getLastUpdatedAt());
        orgResponse.setLastUpdatedBy(saved.getLastUpdatedBy());
        return orgResponse;
    }

    @Transactional
    public OrgResponse updateOrgBasic(Integer orgId, UpdateOrgBasicRequest request, String modifiedBy) {
        Org org = orgRepository.findById(orgId);
        orgHandler.updateBasic(org, request.getName(), request.getLeaderId(), modifiedBy);
        return buildOrgResponse(org);
    }

    @Transactional
    public Integer cancelOrg(Integer orgId, String modifiedBy) {
        Org org = orgRepository.findById(orgId);
        orgHandler.cancel(org, modifiedBy);
        return org.getOrgId();
    }

//    public static void main(String[] args) throws JsonProcessingException {
//        UpdateOrgBasicRequest request = new UpdateOrgBasicRequest();
//        request.setLeaderId(2);
//        request.setName("Banking and Finance Center2");
//        String result = new ObjectMapper().writeValueAsString(request);
//        System.out.println(result);
//    }
}
